package win.smartown.scrollconflict.netease;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * Created by Developer on 2017/11/17.
 */

public class InnerViewPager extends ViewPager {

    private float mLastX;
    private OuterViewPager mOuterViewPager;

    public InnerViewPager(Context context) {
        super(context);
    }

    public InnerViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int action = ev.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mLastX = ev.getX();
                //触摸事件开始，设置父控件不能拦截
                mOuterViewPager.requestDisallowInterceptTouchEvent(true);
                break;
            case MotionEvent.ACTION_MOVE:
                if (getAdapter() != null && getAdapter().getCount() > 1) {
                    if (getAdapter().getCount() - 1 == getCurrentItem()) {
                        //位于最后一个item且继续向右滑动，由父控件拦截处理
                        if (mLastX - ev.getX() > 0) {
                            mOuterViewPager.requestDisallowInterceptTouchEvent(false);
                        } else {
                            mOuterViewPager.requestDisallowInterceptTouchEvent(true);
                        }
                    } else if (getCurrentItem() == 0) {
                        //位于第一个item且继续向左滑动，由父控件拦截处理
                        if (mLastX - ev.getX() < 0) {
                            mOuterViewPager.requestDisallowInterceptTouchEvent(false);
                        } else {
                            mOuterViewPager.requestDisallowInterceptTouchEvent(true);
                        }
                    }
                }
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    public void setOuterViewPager(OuterViewPager outerViewPager) {
        this.mOuterViewPager = outerViewPager;
    }
}
